import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { RequestStatus } from "@/types/request";

interface ApiResponse<T = unknown> {
	code: RequestStatus;
	data: T;
	message: string;
}

// 创建 axios 实例
const service: AxiosInstance = axios.create({
	baseURL: import.meta.env.VITE_API_URL || "/api", // 从环境变量获取 API URL
	timeout: 15000, // 请求超时时间
	headers: {
		"Content-Type": "application/json;charset=utf-8",
	},
});

// 请求拦截器
service.interceptors.request.use(
	(config: AxiosRequestConfig) => {
		// 在这里可以添加token等认证信息
		const token = localStorage.getItem("token");
		if (token) {
			config.headers["Authorization"] = `Bearer ${token}`;
		}
		return config;
	},
	(error: any) => {
		return Promise.reject(error);
	}
);

// 响应拦截器
service.interceptors.response.use(
	(response: AxiosResponse<ApiResponse>) => {
		const { data } = response;
		return data;
	},
	(error: any) => {
		const message = error.response?.data?.message || error.message;
		return Promise.reject(error);
	}
);

// 封装请求方法
export const request = {
	get<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
		return service.get(url, config);
	},

	post<T = unknown>(
		url: string,
		data?: unknown,
		config?: AxiosRequestConfig
	): Promise<ApiResponse<T>> {
		return service.post(url, data, config);
	},

	put<T = unknown>(
		url: string,
		data?: unknown,
		config?: AxiosRequestConfig
	): Promise<ApiResponse<T>> {
		return service.put(url, data, config);
	},

	delete<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
		return service.delete(url, config);
	},

	patch<T = unknown>(
		url: string,
		data?: unknown,
		config?: AxiosRequestConfig
	): Promise<ApiResponse<T>> {
		return service.patch(url, data, config);
	},
};

export default service;
